import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { updateEmployee, addEmployee, getPost } from "@/api/flandre-ui/request";
import moment from "moment";
import { message } from "antd";
import { useTranslation } from "react-i18next";
import { getListSimpleUsers } from "@/api/system/user";
let staffId: String;
let pkId: Number;
const EmployeeDrawer = (props: { register: Fn; reload: Fn; getTitle: string }) => {
	const { t } = useTranslation();
	const en_vi = "HRMS.employeeManagement";
	const employeeFormSchema: FormSchema[] = [
		{
			label: t(`HRMS.leaveApproval.staffName`),
			field: "staffName",
			component: "ApiSelect",
			colProps: { span: 24 },
			componentProps: {
				api: getListSimpleUsers,
				labelField: "nickname",
				valueField: "nickname",
				onChange: (_: any, value: any) => {
					if (!value) return;
					staffId = value.id;
				}
			}
		},
		{
			label: t("kevin_ui.gender"),
			field: "staffSex",
			component: "Select",
			colProps: { span: 24 },
			componentProps: {
				options: [
					{ label: t(`${en_vi}.male`), value: "0" },
					{ label: t(`${en_vi}.female`), value: "1" }
				]
			}
		},
		{
			label: t(`${en_vi}.educationalBackground`),
			field: "jobpozId", //角色
			component: "ApiSelect",
			colProps: { span: 24 },
			componentProps: {
				api: getPost,
				labelField: "definitionEn",
				valueField: "jobpozId"
			}
		},
		{
			label: t(`${en_vi}.birthday`),
			field: "birthday",
			component: "DatePicker",
			colProps: { span: 24 },
			componentProps: { format: "YYYY-MM-DD" }
		},
		{
			label: t(`${en_vi}.age`),
			field: "age", //年龄
			component: "InputNumber",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.educationalBackground`),
			field: "eduLevel", //学历
			component: "Select",
			colProps: { span: 24 },
			componentProps: {
				options: [
					{ label: t(`${en_vi}.primarySchool`), value: "0" },
					{ label: t(`${en_vi}.juniorHighSchool`), value: "1" },
					{ label: t(`${en_vi}.seniorHighSchool`), value: "2" },
					{ label: t(`${en_vi}.JuniorCollege`), value: "3" },
					{ label: t(`${en_vi}.undergraduate`), value: "4" },
					{ label: t(`${en_vi}.master`), value: "5" },
					{ label: t(`${en_vi}.doctor`), value: "6" },
					{ label: t(`${en_vi}.graduateSchool`), value: "7" }
				]
			}
		},
		{
			label: t(`${en_vi}.industryExperience`),
			field: "induExpc", //行业经验
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.personnelLabel`),
			field: "staffTags", //人员标签
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.mobilePhone`),
			field: "phoneNumb", //手机
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.email`),
			field: "emailAddr", //邮箱
			component: "Input",
			colProps: { span: 24 }
		}
	];

	const [registerForm, { validateFields, resetFields, setFieldsValue, updateSchema }] = useForm({
		labelWidth: 120,
		schemas: employeeFormSchema,
		showActionButtonGroup: false
	});

	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, data => {
		resetFields();
		console.log(data);
		if (!data.record) return;
		const record = data.record || {};
		pkId = data.record.pkId;
		updateSchema({
			field: "staffId",
			ifShow: record?.staffId ? true : false,
			componentProps: {
				disabled: true
			}
		});
		// 转换时间字段为 moment 对象
		const transformDate = (dateStr: any) => (dateStr ? moment(dateStr, "YYYY-MM-DD") : null);

		setFieldsValue({
			...record,
			birthday: transformDate(record.birthday),
			startDate: transformDate(record.startDate),
			endDate: transformDate(record.endDate),
			formalDate: transformDate(record.formalDate)
		});
	});

	async function handleSubmit() {
		let values = await validateFields();
		values = {
			...values,
			staffId
		};
		// 转换 moment 对象为字符串格式
		// const formatDate = date => (date && moment.isMoment(date) ? date.format("YYYY-MM-DD") : null);
		if (values.birthday) values.birthday = values.birthday.split(" ")[0];
		if (values.startDate) values.startDate = values.startDate.split(" ")[0];
		if (values.endDate) values.endDate = values.endDate.split(" ")[0];
		if (values.formalDate) values.formalDate = values.formalDate.split(" ")[0];
		// 确保 payload 中的日期字段只传递有效值
		const payload = {
			...values,
			pkId
		};
		try {
			if (props.getTitle === "Edit Employee") {
				await updateEmployee(payload);
				message.success(t("kevin_ui.updateSuccess"));
			} else {
				await addEmployee(values);
				message.success(t("kevin_ui.addedSuccessfully"));
			}
			props.reload();
			closeDrawer();
		} catch (error) {
			message.error(t("kevin_ui.operationFailed"));
		}
	}

	return (
		<BasicDrawer {...props} title={props.getTitle} register={registerDrawer} ok={handleSubmit}>
			<BasicForm register={registerForm} labelWrap={true} />
		</BasicDrawer>
	);
};

export default EmployeeDrawer;
